package br.pucrio.inf.lac.konoha.hyuga.command;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.log4j.Logger;

import com.espertech.esper.adapter.InputAdapter;
import com.espertech.esper.client.EPServiceProvider;
import com.espertech.esperio.AdapterInputSource;
import com.espertech.esperio.csv.CSVInputAdapter;
import com.espertech.esperio.csv.CSVInputAdapterSpec;

import br.pucrio.inf.lac.konoha.hyuga.core.DDSLink;

public class PlayCommand extends Command {

    /** LOGGER. */
    private static Logger LOGGER = Logger.getLogger(PlayCommand.class.getCanonicalName());

    
	public PlayCommand(String commandSTR, EPServiceProvider cepEngine) {
		super(commandSTR, cepEngine);
	}

	@Override
	public void execute() {
		String filename = commandSTR.split(" ")[1];
		
        try {
            // Creating the Playback
            AdapterInputSource source = new AdapterInputSource(readFile(filename));
            CSVInputAdapterSpec spec  = new CSVInputAdapterSpec(source, "CSVLocationUpdateEvent");
            spec.setLooping(false);
            spec.setTimestampColumn("timestamp");
            
            InputAdapter inputAdapter = new CSVInputAdapter(cepEngine, spec);
            
            // Reset Timer
            DDSLink.getInstance().publishMeta("Meta", "ALL", "RESET");

            // Play
            LOGGER.info("Replay Started...");
            long before = System.currentTimeMillis();

            inputAdapter.start();
            
            long after = System.currentTimeMillis();
            long diff  = after - before;
            LOGGER.info("Replay took " + (diff) + " milliseconds");
            LOGGER.info("Replay took " + (diff) / 1000 + " seconds");
            LOGGER.info("Replay took " + (diff) / 1000 / 60 + " minutes");
        } catch (IOException e) {
            LOGGER.error("Unable to read " + filename);
        }
	}

    private InputStream readFile(String filename) throws IOException {
        // Try to load indicated file
        File file = new File(filename);
        InputStream is = null;
        
        if (!file.exists()) {
            LOGGER.warn("File " + filename + " not found in the current directory");
            LOGGER.warn("Trying to load " + filename + " using the classpath");

            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
            if (is != null) {
                LOGGER.info("Loaded parameters from classpath file: " + filename);
            } else {
                LOGGER.error("File " + filename + " does not exist");
                throw new FileNotFoundException();
            }
        } else {
            is = new FileInputStream(file);
            LOGGER.info("Loaded parameters from file: " + file.getName());
        }
        return is;
    }
}
